package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"jin-quan-dev/jinrpc/internal/svc"
	"jin-quan-dev/jinrpc/jinrpc"
	"jin-quan-dev/models/cache"
	"jin-quan-dev/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *jinrpc.ListRequest) (*jinrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("list_%d", in)
	result, _ := cache.RDB.Get(l.ctx, key).Result()
	var list []*jinrpc.FormList
	if result == "" {
		var err error
		list, err = mysql.FormList(mysql.DB, in)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(list)
		cache.RDB.Set(l.ctx, key, jsonData, time.Minute*1)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &jinrpc.ListResponse{
		List: list,
	}, nil
}
